// services/aliyunEmbeddings.js
const { Embeddings } = require("@langchain/core/embeddings");
const axios = require("axios");

/**
 * 阿里云百炼平台嵌入服务实现
 */
class AliyunEmbeddings extends Embeddings {
    constructor(fields) {
        super(fields || {});
        
        // 从环境变量中获取配置
        this.apiKey = process.env.ALIYUN_BAILIAN_API_KEY;
        this.baseUrl = process.env.ALIYUN_BAILIAN_BASE_URL || "https://dashscope.aliyuncs.com/api/v1";
        this.modelName = process.env.ALIYUN_EMBEDDING_MODEL || "text-embedding-v1";
        
        if (!this.apiKey) {
            throw new Error("ALIYUN_BAILIAN_API_KEY 未设置");
        }
        
        console.log(`使用阿里云百炼平台嵌入服务: ${this.modelName}`);
    }

    async embedDocuments(texts) {
        // 对于每个文本，生成嵌入向量
        const embeddings = [];
        for (const text of texts) {
            const embedding = await this.embedQuery(text);
            embeddings.push(embedding);
        }
        return embeddings;
    }

    async embedQuery(text) {
        try {
            console.log(`为文本生成嵌入向量: ${text.substring(0, 50)}...`);
            
            // 调用阿里云百炼平台API生成嵌入向量
            const response = await axios.post(
                `${this.baseUrl}/services/embeddings/text-embedding/text-embedding`,
                {
                    model: this.modelName,
                    input: {
                        texts: [text]
                    }
                },
                {
                    headers: {
                        "Authorization": `Bearer ${this.apiKey}`,
                        "Content-Type": "application/json",
                        "X-DashScope-Async": "disable"
                    }
                }
            );
            
            // 返回嵌入向量
            return response.data.output.embeddings[0].embedding;
        } catch (error) {
            console.error("阿里云百炼平台嵌入API调用失败:", error.message);
            if (error.response) {
                console.error("响应状态:", error.response.status);
                console.error("响应数据:", JSON.stringify(error.response.data, null, 2));
            }
            
            // 如果API调用失败，返回随机向量作为后备方案
            console.log("使用随机向量作为后备方案");
            return Array.from({ length: 1536 }, () => Math.random());
        }
    }
}

// 导出AliyunEmbeddings类
module.exports.AliyunEmbeddings = AliyunEmbeddings;